const db = uniCloud.database();
export function getUserScore() {
	try {
		const startScore = 2000;
		const value = uni.getStorageSync('myScore');
		console.log('myScore:' + value);
		if (value && value >= 0) {
			console.log('myScore1:' + value);
			return value;
		} else {
			console.log('myScore2:' + value);
			uni.setStorageSync('myScore', '' + startScore);
			return startScore;
		}
	} catch (e) {
		// error
		return startScore;
	}
}

// 本地数据
export function addUserScore(score) {
	try {
		let value = uni.getStorageSync('myScore');
		let sum = Number(value) + score;
		console.log('sum:' + sum);
		if (sum < 0) {
			console.log('sum1:' + sum);
			// uni.setStorageSync('myScore', 0);
			uni.showToast({
				title: '积分不够了',
				icon: "none",
				duration: 1500
			})
			return -1;
		} else {
			console.log('sum2:' + sum);
			uni.setStorageSync('myScore', '' + sum);
			return sum;
		}
	} catch (e) {
		// error
		uni.showToast({
			title: '数据异常，请稍后再试',
			icon: "none",
			duration: 1500
		})
		return -1;
	}
}


export function saveUserCloudScoreToLocal(score) {
	uni.setStorageSync("CloudScore", score);
	return getTotalUserScore();
}

// 保存用户增加分数
export function saveUserAddScoreToLocal(score) {
	const total = getTotalUserScore();
	const sum = total + score;
	if (sum < 0) {
		uni.showToast({
			title: '积分不够了',
			icon: "none",
			duration: 1500
		})
	} else {
		const current = uni.getStorageSync('AddScore');
		console.log("saveUserAddScoreToLocal1:",current);
		if (current){
			const addScore = score + current;
			console.log("saveUserAddScoreToLocal1:",addScore);
			uni.setStorageSync("AddScore", addScore);
		}else{
			console.log("saveUserAddScoreToLocal1:",score);
			uni.setStorageSync("AddScore", score);
		}
	}
	return getTotalUserScore();
}

// 获取用户分数
export function getTotalUserScore() {
	const current = uni.getStorageSync('AddScore');
	const currentCloud = uni.getStorageSync('CloudScore');
	const currentScore = Number(current);
	const currentCloudScore = Number(currentCloud);
	console.log("getTotalUserScore:",""+currentCloudScore+","+currentScore);
	if (currentScore && currentCloudScore) {
		return currentScore + currentCloudScore;
	} else {
		if (currentScore) {
			return currentScore;
		} else if (currentCloudScore) {
			return currentCloudScore;
		}
		return 0;
	}
}

// 保存用户分数到云平台
export function saveUserTotalScoreToCloud() {
	const current = uni.getStorageSync('AddScore');
	if(!current || current == 0){
		return;
	}
	const db = uniCloud.database();
	// 获取全部分数
	const total = getTotalUserScore();
	const openid = uni.getStorageSync("UserOpenId");
	const query = db.collection("uni-id-users").where({
		username: openid.toLowerCase()
	});
	query.field('score ,todayAddScore ,last_update_day').get().then(res => {
		if (res.result.data && res.result.data.length) {
			console.log("saveUserTotalScore", total + JSON.stringify(res.result.data));
			let update = {};
			let today = getToday()
			if(res.result.data[0].last_update_day === today){
				update = {
					score: total,
					todayAddScore:todayAddScore+current
				}
			}else{
				update = {
					score: total,
					todayAddScore:current,
					last_update_day:today
				}
			}
			query.update(update).then(res2 => {
				uni.setStorageSync("AddScore", 0);
				saveUserCloudScoreToLocal(total);
			})
		}
	});
}

// 获取用户云储存分数
export async function getUserScoreFromCloud() {
	try {
		const openid = uni.getStorageSync("UserOpenId");
		const userInfo = await db.collection("uni-id-users").where({
			username: openid.toLowerCase()
		}).field('score as score').get();
		console.log("getUserScoreCloud :" + JSON.stringify(userInfo));
		return userInfo.result.data[0].score;
	} catch (e) {
		console.log("getUserScoreCloud error:" + e);
		return -1;
	}
}

export function getToday(){
	return  ""+new Date().getFullYear() + (new Date().getMonth()+1)+ new Date().getDate();
}

// 签到分数
export function SignInGetScore() {
	try {
		const value = uni.getStorageSync('SignIn');
		const today = getToday()
		if (value === today) {
			uni.showToast({
				title: '已签到，明天再来试试吧',
				icon: "none",
				duration: 1500
			})
			return getTotalUserScore();
		} else {
			uni.showToast({
				title: '签到成功',
				icon: "success",
				duration: 1500
			})
			uni.setStorageSync('SignIn', today)
			const value = uni.getStorageSync('AddScore');
			if (value) {
				uni.setStorageSync('AddScore', Number(value) + 200)
			} else {
				uni.setStorageSync('AddScore', 200);
			}
		}
		return getTotalUserScore();
	} catch (e) {
		// error
		console.log('myScore' + e);
		return getTotalUserScore();
	}
}


// 本地版签到分数
export function SignInGetScoreLocal() {
	let today = getToday()
	try {
		const value = uni.getStorageSync('SignIn');
		if (value === today) {
			uni.showToast({
				title: '已签到，明天再来试试吧',
				icon: "none",
				duration: 1500
			})
			return getUserScore();
		} else {
			uni.showToast({
				title: '签到成功',
				icon: "success",
				duration: 1500
			})
			uni.setStorageSync('SignIn', today)
			const value = uni.getStorageSync('myScore');
			if (value && value > 0) {
				uni.setStorageSync('myScore', Number(value) + 200)
			} else {
				uni.setStorageSync('myScore', 200);
			}
		}
		return getUserScore();
	} catch (e) {
		// error
		console.log('myScore' + e);
		return getUserScore();
	}
}